package com.ckr.controller;

import com.ckr.dao.DepartmentDao;
import com.ckr.dao.EmployeeDao;
import com.ckr.pojo.Department;
import com.ckr.pojo.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Collection;

/**
 * @author Shadowckr
 * @create 2022-01-14 17:38
 */

@Controller
public class EmployeeController {
    @Resource
    private EmployeeDao employeeDao;
    @Resource
    private DepartmentDao departmentDao;

    @RequestMapping("/employees")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAllEmployees();
        model.addAttribute("emps", employees);
        return "emp/list";//返回到list页面
    }

    @GetMapping("/add")
    public String toAddPage(Model model) {
        //查出所有的部门信息，添加到departments中，用于前端接收
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments", departments);
        return "emp/add";//返回到添加员工页面
    }

    //增加
    //接收前端传递的参数，自动封装成为对象[要求前端传递的参数名和属性名一致]
    @PostMapping("/add")
    public String addEmployee(Employee employee) {
        employeeDao.addEmployee(employee);//添加一个员工
        return "redirect:/employees";//重定向到/employees，刷新列表，返回到list页面
    }

    //restful风格接收参数
    @RequestMapping("/edit/{id}")
    public String toEditPage(@PathVariable("id") int id, Model model) {
        //查询指定id的员工，用于前端接收
        Employee employee = employeeDao.getEmployeeByID(id);
        model.addAttribute("employee", employee);
        //查出所有的部门信息，添加到departments中，用于前端接收
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments", departments);
        return "emp/edit";//返回到编辑员工页面
    }

    //修改
    //提交修改后的表单
    @PostMapping("/update")
    public String update(Employee employee) {
        //修改一个员工
        //Map（HashMap）:修改: put(Object key, Object value)
        employeeDao.addEmployee(employee);
        return "redirect:/employees";
    }

    //删除
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        employeeDao.deleteEmployeeByID(id);
        return "redirect:/employees";
    }

    //注销
    @RequestMapping("/user/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index.html";
    }
}
